import React, { useEffect, useState } from 'react';
import moment from 'moment';
import { Button } from 'antd';
import { fetchProcess } from '@/services/flowMine/waitApprovals';
import { getCompanyOfferDetail } from '@/services/myRecruit/offerDetail';
import { getOrganization } from '@/utils/utils';

import FlowStep from './Steps';
import styles from './Print.less';

// eslint-disable-next-line react/no-danger
const empty = <span dangerouslySetInnerHTML={{ __html: '&nbsp' }} />; // 要不然会换行？
const formatDate = date => moment(date || null).format('YYYY-MM-DD');

const Print = ({ location }) => {
    const {
        query: { offerCode }
    } = location;

    const [detail, setDetail] = useState({});
    const [approval, setApproval] = useState([]);

    const fetchData = async () => {
        const detailResult = await getCompanyOfferDetail(offerCode);
        if (detailResult.code !== 10000) return;
        setDetail(detailResult.data);
        const approvalResult = await fetchProcess(detailResult.data.applicationNo);
        if (approvalResult.code !== 10000) return;
        setApproval(approvalResult.data);
    };

    useEffect(() => {
        if (offerCode) fetchData();
    }, [offerCode]);

    const isSingapore = getOrganization(detail.companyId)?.area !== 'cn';

    const fieldsMap1 = [
        {
            label: '录用人姓名',
            key: 'talentName'
        },
        {
            label: '性别',
            key: 'talentSexName'
        },
        {
            label: '出生年月',
            key: 'talentBirth',
            render: () => (typeof detail.talentBirth === 'object' ? undefined : detail.talentBirth)
        },
        {
            label: '最高学历',
            key: 'talentAgreeName'
        },
        {
            label: '录用部门',
            key: 'departmentName'
        },
        {
            label: '录用职位',
            key: 'entryPostName'
        },
        {
            label: '职级',
            key: 'entryLevel'
        },
        {
            label: '入职时间',
            key: 'entryDate',
            render: () => formatDate(detail.entryDate)
        },
        {
            label: '同岗经验/年',
            key: 'talentExperience'
        },
        {
            label: '试用期带教人',
            key: 'teacherName'
        }
    ];

    const fieldsMap2 = [
        {
            label: '原单位月薪',
            key: 'oldMonthSalary'
        },
        {
            label: '原综合年薪',
            key: 'oldYearSalary'
        },
        {
            label: '现月薪(税前)',
            key: 'monthSalary'
        },
        {
            label: '现综合年薪',
            key: 'yearSalary'
        },
        {
            label: '季度绩效奖金(税前)',
            key: 'seasonPrize'
        },
        {
            label: '年薪涨幅',
            key: 'gainPercent',
            render: () => `${detail.gainPercent}%`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
        },
        {
            label: '半年奖金(税前)',
            key: 'halfPrize'
        },
        {
            label: '年终服务奖金(税前)',
            key: 'yearPrize'
        },
        {
            label: '劳动合同开始时间',
            key: 'contractBeginDate'
        },
        {
            label: '试用期长度',
            key: 'tryDurationName'
        },
        {
            label: '申请理由说明',
            key: 'remark',
            render: () => <span className={styles.hidden}>{detail.remark}</span>
        }
    ];

    const sgFieldsMap1 = [
        {
            label: '录用人姓名',
            key: 'talentName'
        },
        {
            label: '性别',
            key: 'talentSexName'
        },
        {
            label: '出生年月',
            key: 'talentBirth',
            render: () => (typeof detail.talentBirth === 'object' ? undefined : detail.talentBirth)
        },
        {
            label: '入职时间',
            key: 'entryDate'
        },
        {
            label: '录用部门',
            key: 'departmentName'
        },
        {
            label: '录用职位',
            key: 'entryPostName'
        },
        {
            label: '职级',
            key: 'entryLevel'
        }
    ];

    const sgFieldsMap2 = [
        {
            label: '原单位月薪',
            key: 'oldMonthSalary'
        },
        {
            label: '原综合年薪',
            key: 'oldYearSalary'
        },
        {
            label: 'AWS',
            key: 'awsName'
        },
        {
            label: '原花红',
            key: 'originalBonus'
        },
        {
            label: '月薪',
            key: 'monthSalary'
        },
        {
            label: '涨幅',
            key: 'gainPercent',
            render: () => `${detail.gainPercent}%`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
        },
        {
            label: '是否缴纳公积金',
            key: 'accumulationFundTypeName'
        },
        {
            label: '劳动合同开始时间',
            key: 'contractBeginDate',
            render: () => formatDate(detail.contractBeginDate)
        },
        {
            label: '试用期长度',
            key: 'tryDurationName'
        },
        {
            label: '申请理由说明',
            key: 'remark',
            render: () => <span className={styles.hidden}>{detail.remark}</span>
        },
        {
            label: '离职通知期(转正前)',
            key: 'probationQuitNoticeName'
        },
        {
            label: '离职通知期(转正后)',
            key: 'regularQuitNoticeName'
        }
    ];

    const renderItem = item => {
        const { label, key, render } = item;
        const value = render ? render() : detail[key] || empty;
        return (
            <>
                <em>{label}: </em>
                {value}
            </>
        );
    };

    const renderTable = rows =>
        rows.map((item, index) => {
            if (index % 2 === 0) {
                return (
                    <tr key={item.key}>
                        <td>{rows[index] ? renderItem(rows[index]) : null}</td>
                        <td>{rows[index + 1] ? renderItem(rows[index + 1]) : null}</td>
                    </tr>
                );
            }
            return null;
        });

    const renderContent = (cfg = []) =>
        cfg.map(list => (
            <div className={styles.section} key={list.title}>
                <h3 className={styles.mainTitle}>{list.title}</h3>
                <table>
                    <tbody>{renderTable(list.fields)}</tbody>
                </table>
            </div>
        ));

    return (
        <div className={styles.wrap}>
            <div>
                <Button className={styles.btn} onClick={() => window.print()}>
                    打印
                </Button>
            </div>
            {renderContent([
                {
                    title: '录用信息',
                    fields: isSingapore ? sgFieldsMap1 : fieldsMap1
                },
                {
                    title: '薪资福利',
                    fields: isSingapore ? sgFieldsMap2 : fieldsMap2
                }
            ])}
            <div className={styles.section}>
                <h3 className={styles.mainTitle}>审批流程</h3>
                <div style={{ padding: '8px 0 20px 20px' }}>
                    申请主题： offer申请流程-{detail.companyName}-{detail.talentName}
                </div>
                <FlowStep data={approval} />
            </div>
        </div>
    );
};

export default Print;
